import { useEffect, useState } from 'react';
import { detectDevice, type DeviceInfoType } from '@/utils/device';

export const useDevice = () => {
  const [device, setDevice] = useState<DeviceInfoType>();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // 初始检测设备类型
    const updateDevice = () => {
      const { type } = detectDevice();
      setDevice(type);
      setIsLoading(false);
    };

    // 首次检测
    updateDevice();

    // 监听窗口大小变化
    const handleResize = () => {
      updateDevice();
    };

    window.addEventListener('resize', handleResize);

    // 清理事件监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return { device, isLoading };
};
